<template>
  <div class="message-input" :class="{ 'keyboard-active': isKeyboardActive }">
    <input
      v-model="messageText"
      type="text"
      placeholder="请输入消息..."
      @keyup.enter="sendMessage"
      @focus="onFocus"
      @blur="onBlur"
    >
    <button @click="sendMessage">发送</button>
  </div>
</template>

<script setup lang="ts">
import { ref, onMounted, onUnmounted } from 'vue'
import { useChatStore } from '../stores/chat'

const store = useChatStore()
const messageText = ref('')
const isKeyboardActive = ref(false)

// 添加键盘高度监听
const updateKeyboardHeight = () => {
  const visualViewport = window.visualViewport
  if (visualViewport) {
    const height = visualViewport.height
    const windowHeight = window.innerHeight
    const keyboardHeight = windowHeight - height
    document.documentElement.style.setProperty('--keyboard-height', `${keyboardHeight}px`)
  }
}

onMounted(() => {
  window.visualViewport?.addEventListener('resize', updateKeyboardHeight)
})

onUnmounted(() => {
  window.visualViewport?.removeEventListener('resize', updateKeyboardHeight)
})

const sendMessage = () => {
  if (messageText.value.trim()) {
    store.addMessage(messageText.value)
    messageText.value = ''
  }
}

const onFocus = () => {
  isKeyboardActive.value = true
  document.body.classList.add('keyboard-active')
  // 滚动到底部
  setTimeout(() => {
    window.scrollTo(0, document.body.scrollHeight)
  }, 100)
}

const onBlur = () => {
  isKeyboardActive.value = false
  document.body.classList.remove('keyboard-active')
}
</script>

<style scoped>
.message-input {
  display: flex;
  padding: 1rem;
  border-top: 1px solid #ddd;
  background: #fff;
  position: relative;
  z-index: 100;
}

.keyboard-active {
  position: fixed;
  bottom: 0;
  left: 0;
  right: 0;
  transition: transform 0.3s ease-out;
  transform: translateY(calc(-1 * var(--keyboard-height, 0px)));
}

input {
  flex: 1;
  padding: 0.5rem;
  border: 1px solid #ddd;
  border-radius: 4px;
  margin-right: 0.5rem;
  font-size: 16px; /* 防止 iOS 自动缩放 */
}

button {
  padding: 0.5rem 1rem;
  background: #007bff;
  color: white;
  border: none;
  border-radius: 4px;
  cursor: pointer;
}

button:hover {
  background: #0056b3;
}

@media (max-width: 768px) {
  .message-input {
    padding: 0.5rem;
  }
  
  input {
    padding: 0.5rem;
  }
  
  button {
    padding: 0.5rem 0.75rem;
  }
}

/* 添加 iOS 安全区域适配 */
@supports (padding-bottom: env(safe-area-inset-bottom)) {
  .message-input {
    padding-bottom: calc(0.5rem + env(safe-area-inset-bottom));
  }
}
</style> 